package com.kg.tombs.utils;

import io.vertx.core.json.JsonObject;
import org.apache.poi.ss.usermodel.*;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class ExcelParser {

    public static List<JsonObject> parse(InputStream is){
        List<JsonObject> list = new ArrayList<>();
        try (Workbook workbook = WorkbookFactory.create(is)) {
            int sheetNums = workbook.getNumberOfSheets();
            for (int s = 0; s < sheetNums; s++) {
                Sheet sheet = workbook.getSheetAt(s);
                if (sheet.getLastRowNum() < 1) {
                    continue;
                }
//                String sheetName = sheet.getSheetName();
//                String defaultName = "Sheet" + (s+1);
//                if(sheetName.equals(defaultName)){
//                    sheetName = null;
//                }
                // 获取表头行
                Row headerRow = sheet.getRow(0);
                if (headerRow == null) {
                    continue;
                }

                // 解析数据行
                for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                    Row row = sheet.getRow(i);
                    if (row == null) {
                        continue;
                    }

                    JsonObject jsonObject = new JsonObject();
                    for (int j = 0; j < headerRow.getLastCellNum(); j++) {
                        Cell headerCell = headerRow.getCell(j);
                        Cell dataCell = row.getCell(j);

                        String headerKey = getStringValue(headerCell);
                        String dataValue = getStringValue(dataCell);

                        // 使用表头作为key，去除内容中的空白符
                        if (!headerKey.isEmpty()) {
                            jsonObject.put(headerKey, dataValue);
                        }
                    }
//                    if(!Objects.isNull(sheetName)){
//                        jsonObject.put("组", sheetName);
//                    }
                    list.add(jsonObject);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    private static String getStringValue(Cell cell) {
        if (cell == null) {
            return "";
        }
        cell.setCellType(CellType.STRING);
        String value = cell.getStringCellValue().trim();
        if ("无".equals(value)) {
            return "";
        }
        return value.replaceAll("\\s+", "");
    }

}
